<template>
  <div class="page-header">
    <h2 class="page-title">
      <el-icon class="title-icon"><Money /></el-icon>
      报销申请
    </h2>
    <el-button type="primary" @click="saveAsDraft">
      <el-icon><Document /></el-icon>
      保存草稿
    </el-button>
  </div>

  <!-- 申请表单 -->
  <el-card class="form-card" shadow="hover">
    <template #header>
      <div class="card-header">
        <span>报销信息</span>
        <el-tag type="info">请填写完整的报销信息</el-tag>
      </div>
    </template>

    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      class="reimbursement-form"
    >
      <!-- 基本信息 -->
      <div class="form-section">
        <h3 class="section-title">基本信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="申请人" prop="applicant">
              <el-input v-model="formData.applicant" placeholder="请输入申请人姓名" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="department">
              <el-input v-model="formData.department" placeholder="请输入部门名称" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input v-model="formData.position" placeholder="请输入职位" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 报销信息 -->
      <div class="form-section">
        <h3 class="section-title">报销信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报销类型" prop="reimbursementType">
              <el-select
                v-model="formData.reimbursementType"
                placeholder="请选择报销类型"
                style="width: 100%"
              >
                <el-option label="差旅费" value="travel" />
                <el-option label="办公用品" value="office" />
                <el-option label="业务招待" value="entertainment" />
                <el-option label="培训费用" value="training" />
                <el-option label="通讯费用" value="communication" />
                <el-option label="其他费用" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报销日期" prop="reimbursementDate">
              <el-date-picker
                v-model="formData.reimbursementDate"
                type="date"
                placeholder="选择报销日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="报销事由" prop="reason">
              <el-input
                v-model="formData.reason"
                type="textarea"
                :rows="3"
                placeholder="请详细说明报销事由"
                maxlength="300"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 费用明细 -->
      <div class="form-section">
        <h3 class="section-title">
          费用明细
          <el-button type="primary" size="small" @click="addExpenseItem" style="margin-left: 16px">
            <el-icon><Plus /></el-icon>
            添加费用项
          </el-button>
        </h3>

        <div v-for="(item, index) in formData.expenseItems" :key="index" class="expense-item">
          <div class="expense-item-header">
            <span>费用项 {{ index + 1 }}</span>
            <el-button
              type="danger"
              size="small"
              @click="removeExpenseItem(index)"
              :disabled="formData.expenseItems.length === 1"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </div>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item
                :label="'费用名称'"
                :prop="`expenseItems.${index}.name`"
                :rules="expenseItemRules.name"
              >
                <el-input v-model="item.name" placeholder="请输入费用名称" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                :label="'费用金额'"
                :prop="`expenseItems.${index}.amount`"
                :rules="expenseItemRules.amount"
              >
                <el-input-number
                  v-model="item.amount"
                  :min="0"
                  :precision="2"
                  style="width: 100%"
                  placeholder="费用金额"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                :label="'费用分类'"
                :prop="`expenseItems.${index}.category`"
                :rules="expenseItemRules.category"
              >
                <el-select v-model="item.category" placeholder="请选择费用分类" style="width: 100%">
                  <el-option label="交通费" value="transport" />
                  <el-option label="住宿费" value="accommodation" />
                  <el-option label="餐饮费" value="meal" />
                  <el-option label="办公费" value="office" />
                  <el-option label="通讯费" value="communication" />
                  <el-option label="其他" value="other" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                :label="'发生日期'"
                :prop="`expenseItems.${index}.date`"
                :rules="expenseItemRules.date"
              >
                <el-date-picker
                  v-model="item.date"
                  type="date"
                  placeholder="选择发生日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="'备注'" :prop="`expenseItems.${index}.remark`">
                <el-input v-model="item.remark" placeholder="请输入备注信息" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 费用汇总 -->
        <div class="expense-summary">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="summary-item">
                <span class="summary-label">费用项数：</span>
                <span class="summary-value">{{ formData.expenseItems.length }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="summary-item">
                <span class="summary-label">总金额：</span>
                <span class="summary-value total-amount">¥{{ totalAmount }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="summary-item">
                <span class="summary-label">大写：</span>
                <span class="summary-value">{{ amountInWords }}</span>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 发票上传 -->
      <div class="form-section">
        <h3 class="section-title">发票上传</h3>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="发票附件">
              <el-upload
                ref="uploadRef"
                :action="uploadUrl"
                :headers="uploadHeaders"
                :file-list="fileList"
                :on-preview="handleFilePreview"
                :on-remove="handleFileRemove"
                :before-remove="beforeFileRemove"
                :on-success="handleFileSuccess"
                :on-error="handleFileError"
                multiple
                :limit="10"
                list-type="picture-card"
                accept=".jpg,.jpeg,.png,.pdf"
              >
                <el-icon><Plus /></el-icon>
                <template #tip>
                  <div class="el-upload__tip">
                    支持jpg/png/pdf格式，单个文件不超过10MB，请上传清晰的发票照片或扫描件
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 审批流程 -->
      <div class="form-section">
        <h3 class="section-title">审批流程</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="直接上级" prop="directManager">
              <el-select
                v-model="formData.directManager"
                placeholder="请选择直接上级"
                style="width: 100%"
              >
                <el-option label="张经理" value="zhang" />
                <el-option label="李总监" value="li" />
                <el-option label="王总" value="wang" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="财务审批" prop="financeApprover">
              <el-select
                v-model="formData.financeApprover"
                placeholder="请选择财务审批人"
                style="width: 100%"
              >
                <el-option label="陈财务" value="chen" />
                <el-option label="刘财务" value="liu" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <el-button @click="resetForm">重置</el-button>
        <el-button type="info" @click="saveAsDraft">保存草稿</el-button>
        <el-button type="primary" @click="submitForm">提交申请</el-button>
      </div>
    </el-form>
  </el-card>

  <!-- 报销统计 -->
  <el-card class="stats-card" shadow="hover">
    <template #header>
      <div class="card-header">
        <span>报销统计</span>
      </div>
    </template>

    <el-row :gutter="20">
      <el-col :span="6">
        <div class="stat-item">
          <div class="stat-icon total-icon">
            <el-icon><Money /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ reimbursementStats.total }}</div>
            <div class="stat-label">总报销次数</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-item">
          <div class="stat-icon amount-icon">
            <el-icon><Wallet /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">¥{{ reimbursementStats.amount }}</div>
            <div class="stat-label">总报销金额</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-item">
          <div class="stat-icon pending-icon">
            <el-icon><Timer /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ reimbursementStats.pending }}</div>
            <div class="stat-label">待审批</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-item">
          <div class="stat-icon approved-icon">
            <el-icon><Check /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ reimbursementStats.approved }}</div>
            <div class="stat-label">已通过</div>
          </div>
        </div>
      </el-col>
    </el-row>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules, UploadUserFile } from 'element-plus'
import { Money, Document, Plus, Delete, Wallet, Timer, Check } from '@element-plus/icons-vue'

// 表单引用
const formRef = ref<FormInstance>()
const uploadRef = ref()

// 表单数据
const formData = reactive({
  applicant: '张三',
  department: '技术部',
  position: '前端工程师',
  phone: '13800138000',
  reimbursementType: '',
  reimbursementDate: '',
  reason: '',
  expenseItems: [
    {
      name: '',
      amount: 0,
      category: '',
      date: '',
      remark: '',
    },
  ],
  directManager: '',
  financeApprover: '',
})

// 费用项验证规则
const expenseItemRules = {
  name: [{ required: true, message: '请输入费用名称', trigger: 'blur' }],
  amount: [
    { required: true, message: '请输入费用金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '费用金额必须大于0', trigger: 'blur' },
  ],
  category: [{ required: true, message: '请选择费用分类', trigger: 'change' }],
  date: [{ required: true, message: '请选择发生日期', trigger: 'change' }],
}

// 表单验证规则
const formRules: FormRules = {
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
  ],
  reimbursementType: [{ required: true, message: '请选择报销类型', trigger: 'change' }],
  reimbursementDate: [{ required: true, message: '请选择报销日期', trigger: 'change' }],
  reason: [
    { required: true, message: '请输入报销事由', trigger: 'blur' },
    { min: 10, message: '报销事由至少10个字符', trigger: 'blur' },
  ],
  directManager: [{ required: true, message: '请选择直接上级', trigger: 'change' }],
  financeApprover: [{ required: true, message: '请选择财务审批人', trigger: 'change' }],
}

// 文件上传相关
const fileList = ref<UploadUserFile[]>([])
const uploadUrl = '/api/upload'
const uploadHeaders = {
  Authorization: 'Bearer token',
}

// 报销统计
const reimbursementStats = reactive({
  total: 25,
  amount: '28,560',
  pending: 3,
  approved: 22,
})

// 计算总金额
const totalAmount = computed(() => {
  return formData.expenseItems.reduce((sum, item) => sum + (item.amount || 0), 0).toFixed(2)
})

// 金额转大写
const amountInWords = computed(() => {
  const amount = parseFloat(totalAmount.value)
  if (amount === 0) return '零元整'

  const digits = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
  const units = ['', '拾', '佰', '仟']
  // const bigUnits = ['', '万', '亿']

  const numToChinese = (num: number) => {
    if (num === 0) return ''
    let result = ''
    let unitIndex = 0

    while (num > 0) {
      const digit = num % 10
      if (digit !== 0) {
        result = digits[digit] + units[unitIndex] + result
      } else if (result && !result.startsWith('零')) {
        result = '零' + result
      }
      num = Math.floor(num / 10)
      unitIndex++
    }

    return result
  }

  const yuan = Math.floor(amount)
  const jiao = Math.round((amount - yuan) * 100)

  let result = ''
  if (yuan > 0) {
    result = numToChinese(yuan) + '元'
  }
  if (jiao > 0) {
    result += numToChinese(jiao) + '角'
  } else {
    result += '整'
  }

  return result
})

// 添加费用项
const addExpenseItem = () => {
  formData.expenseItems.push({
    name: '',
    amount: 0,
    category: '',
    date: '',
    remark: '',
  })
}

// 删除费用项
const removeExpenseItem = (index: number) => {
  if (formData.expenseItems.length > 1) {
    formData.expenseItems.splice(index, 1)
  }
}

// 文件上传处理
const handleFilePreview = (file: UploadUserFile) => {
  console.log(file)
}

const handleFileRemove = (file: UploadUserFile, fileList: UploadUserFile[]) => {
  console.log(file, fileList)
}

const beforeFileRemove = (file: UploadUserFile) => {
  return ElMessageBox.confirm(`确定移除 ${file.name}？`)
}

const handleFileSuccess = () => {
  ElMessage.success('文件上传成功')
}

const handleFileError = () => {
  ElMessage.error('文件上传失败')
}

// 表单操作
const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
  fileList.value = []
  // 重置费用项
  formData.expenseItems = [
    {
      name: '',
      amount: 0,
      category: '',
      date: '',
      remark: '',
    },
  ]
}

const saveAsDraft = () => {
  ElMessage.success('草稿保存成功')
}

const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    // 验证费用项
    for (let i = 0; i < formData.expenseItems.length; i++) {
      const item = formData.expenseItems[i]
      if (!item.name || !item.amount || !item.category || !item.date) {
        ElMessage.error(`请完善第${i + 1}项费用信息`)
        return
      }
    }

    // 验证总金额
    const total = parseFloat(totalAmount.value)
    if (total <= 0) {
      ElMessage.error('总金额必须大于0')
      return
    }

    // 模拟提交
    ElMessage.success('报销申请提交成功')
    resetForm()
  } catch (error) {
    ElMessage.error('请检查表单信息')
  }
}

// 初始化
onMounted(() => {
  // 可以在这里加载用户信息和报销统计
})
</script>

<style scoped lang="less">
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .page-title {
    display: flex;
    align-items: center;
    margin: 0;
    color: #303133;
    font-size: 24px;
    font-weight: 600;

    .title-icon {
      margin-right: 8px;
      color: #409eff;
    }
  }
}

.form-card {
  margin-bottom: 20px;
  border-radius: 8px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
  }

  .reimbursement-form {
    .form-section {
      margin-bottom: 30px;
      padding-bottom: 20px;
      border-bottom: 1px solid #ebeef5;

      &:last-child {
        border-bottom: none;
      }

      .section-title {
        margin: 0 0 20px 0;
        color: #303133;
        font-size: 18px;
        font-weight: 600;
        position: relative;
        padding-left: 12px;
        display: flex;
        align-items: center;

        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 4px;
          height: 18px;
          background-color: #409eff;
          border-radius: 2px;
        }
      }

      .expense-item {
        background-color: #f8f9fa;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 16px;
        border: 1px solid #e9ecef;

        .expense-item-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;
          padding-bottom: 12px;
          border-bottom: 1px solid #dee2e6;
          font-weight: 600;
          color: #495057;
        }
      }

      .expense-summary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 8px;
        padding: 20px;
        color: white;

        .summary-item {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .summary-label {
            font-size: 14px;
            opacity: 0.9;
          }

          .summary-value {
            font-size: 16px;
            font-weight: 600;

            &.total-amount {
              font-size: 20px;
              color: #ffd700;
            }
          }
        }
      }
    }

    .form-actions {
      display: flex;
      justify-content: center;
      gap: 16px;
      margin-top: 30px;
      padding-top: 20px;
      border-top: 1px solid #ebeef5;
    }
  }
}

.stats-card {
  border-radius: 8px;

  .card-header {
    font-weight: 600;
  }

  .stat-item {
    display: flex;
    align-items: center;
    padding: 20px;
    background-color: #f8f9fa;
    border-radius: 8px;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .stat-icon {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16px;
      font-size: 24px;
      color: white;

      &.total-icon {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }

      &.amount-icon {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      }

      &.pending-icon {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      }

      &.approved-icon {
        background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
      }
    }

    .stat-content {
      .stat-value {
        font-size: 24px;
        font-weight: 700;
        color: #303133;
        margin-bottom: 4px;
      }

      .stat-label {
        font-size: 14px;
        color: #909399;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .reimbursement-container {
    padding: 10px;

    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;

      .page-title {
        font-size: 20px;
      }
    }

    .form-card {
      .reimbursement-form {
        .form-section {
          .section-title {
            font-size: 16px;
          }

          .expense-item {
            padding: 16px;
          }

          .expense-summary {
            padding: 16px;
          }
        }

        .form-actions {
          flex-direction: column;
          align-items: center;
        }
      }
    }

    .stats-card {
      .stat-item {
        margin-bottom: 16px;
      }
    }
  }
}
</style>
